#include "thread_pool.h"
#include "sqlpool.h"
//删除文件
void rmFile(SQL_NODE* conn, int fileId)
{
    char bufSql[256];
    sprintf(bufSql, "DELETE FROM virtual_file WHERE vfb_id=%d", fileId);
    if(mysql_query(&conn->fd, bufSql))
    {
        fprintf(stderr, "fail to delete file:%s", mysql_error(&conn->fd));
    }
}

//递归删除目录及其内容
void rmdirRecursive(SQL_NODE* conn, int dirId)
{
    char bufSql[256];
    MYSQL_RES* result;
    MYSQL_ROW row;

    //删除所有子文件
    sprintf(bufSql, "SELECT vfb_id FROM virtual_file WHERE parent_id=%d", dirId);
    if (mysql_real_query(&conn->fd, bufSql, strlen(bufSql))) 
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(&conn->fd));
        return;
    }

    result = mysql_store_result(&conn->fd);
    if(!result)
    {
        fprintf(stderr, "Failed to store result: %s\n", mysql_error(&conn->fd));
        return;
    }

    while((row = mysql_fetch_row(result)))
    {
        int childId = atoi(row[0]);
        //递归删除子目录和子文件
        rmdirRecursive(conn, childId);
    }
    mysql_free_result(result);
    //删除目录本身
    rmFile(conn, dirId);
}

//处理删除请求
void rmCommand(task_t * task)
{
    printf("execute rmdir command.\n");
    SQL_NODE* conn;
    //从连接池获取连接
    conn = get_db_connect(task->sp);

    char bufSql[256];
    //获取用户当前目录
    int uid = 0;
    int pathId = 0;
    mkdir_get_dir_id(task->sp, task->name, &uid, &pathId);
    snprintf(bufSql, sizeof(bufSql),
             "SELECT vfb_id, type FROM virtual_file WHERE parent_id=%d AND owner_id=%d AND filename='%s'",
             pathId, uid, task->data);

    if(mysql_query(&conn->fd, bufSql))
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(&conn->fd));
        send(task->peerfd, "ERROR", 6, 0);
        release_node(task->sp, conn);
        return;
    }

    printf("bufSql: %s\n", bufSql);
    MYSQL_RES *result = mysql_store_result(&conn->fd);
    if(!result)
    {
        fprintf(stderr, "store result failed:%s\n", mysql_error(&conn->fd));
        send(task->peerfd, "ERROR", 6, 0);
        release_node(task->sp, conn); // 归还连接
        return;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if(row)
    {
        printf("%s %s\n", row[0], row[1]);
        int fileId = atoi(row[0]);
        const char* fileType = row[1];

        if(strcmp(fileType, "f") == 0)
        {
            //文件：直接删除
            rmFile(conn, fileId);
        }
        else if(strcmp(fileType, "d") == 0)
        {
            //目录：递归删除
            rmdirRecursive(conn, fileId);
        }
        else
        {
            //其他类型
            fprintf(stderr, "Unexpected type : %s", fileType);
        }
	}
    else
    {
        //未找到文件或目录
        send(task->peerfd, "Not found", 10, 0);
    }

    mysql_free_result(result);
    release_node(task->sp, conn);
    
}

